<?php

require __DIR__ . '/../vendor/autoload.php';

use Web3\Providers\HttpProvider;
use Web3\RequestManagers\HttpRequestManager;
use Web3\Web3;
use Web3p\EthereumTx\Transaction;

$url = 'https://ropsten.infura.io/v3/8f762549c8c341388ac03552835a0358';
$web3 = new Web3(new HttpProvider(new HttpRequestManager($url, 15)));

$account1 = '0x9Ba6EC8fA4CD0AC4b805c605cEBE4901046c4041';
$account2 = '0xDF7C5453DFFf67579cF74A148424fE2d366E21C3';

$privateKey1 = '85505aa1c1b634c60a24f94dd7209fa8bda2fd46179b15080eff427b0b320a85';
$privateKey2 = 'b109c576f6385f7f740dbae9c12dd109a4f47877a58ae0e738e6ac669dffdf75';

$web3->getEth()->getTransactionCount($account1, function ($err, $res) use ($web3, $account2, $privateKey1) {
    if ($err) {
        return;
    }
    $txCount = '0x' . $web3->getUtils()->toHex($res);

    $wei = $web3->getUtils()->toWei('0.1', 'ether');
    $value = '0x' . $web3->getUtils()->toHex($wei->toString());

    $gasLimit = '0x' . $web3->getUtils()->toHex(21000);

    $wei = $web3->getUtils()->toWei('10', 'gwei');
    $gasPrice = '0x' . $web3->getUtils()->toHex($wei->toString());

    $txObject = [
        'nonce'    => $txCount,
        'to'       => $account2,
        'value'    => $value,
        'gasLimit' => $gasLimit,
        'gasPrice' => $gasPrice,
        'chainId'  => 3,
    ];

    $tx = new Transaction($txObject);
    $raw = $tx->sign($privateKey1);

    $web3->getEth()->sendRawTransaction('0x' . $raw, function ($err, $res) {
        if ($err !== null) {
            echo 'Error: ' . $err->getMessage() . PHP_EOL;
            return;
        }

        var_dump('hash: ' . $res);
    });
});
